import Promisify from '../../utils/promisify'
import { updateUserInfoById, loginWechat } from '../../apis/user'
import { logout, getUID, login, isLogin,setSTATUS } from '../../utils/permission'

var app = getApp()

Page({
  data: {
    showLoginBtn: false,
    userInfo: {},
  },

  onLoad: function () {
    getApp().getUserInfo().then(res=>{
      this.setData({ userInfo:res});
    })
    // 获取用户授权，更新用户昵称与头像
     Promisify(wx.getUserInfo)()
      .catch(() => {
        this.setData({ showLoginBtn: true });
      });
      
    // Promisify(wx.getUserInfo)()
    //   .then(this._updateUserInfo)
    //   .catch(() => {
    //     this.setData({ showLoginBtn: true });
    //   })
  },

  onLogout: function () {
    wx.showModal({
      content: '确定退出登录？',
      success: res => {
        if (res.confirm && logout()) {
          wx.reLaunch({ url: '/pages/register/register' })
        }
      }
    })
  },
  /**
    * 跳转页面前判断是否登录，如果没有登录，显示登录对话框
    */
  onNavigate: function (e) {
    if (!isLogin(true)) {
      return
    }
    let target = e.currentTarget.dataset.target;

    let url;

    switch (target) {
      case 'qrcode':
        url = './children/qrcode';
        break
      case 'order-ongoing':
        url = './children/order-ongoing';
        break
      case 'order-history':
        url = './children/order-history';
        break
      case 'review':
        url = './children/review'
        break
    }
    wx.navigateTo({ url: url })
  },
  onClickLoginBtn: function (e) {
    console.log('hh',e)
    let { errMsg } = e.detail
    if (errMsg.indexOf('fail') === -1) {
      this._updateUserInfo(e.detail).then(() => {
        
        this.setData({ showLoginBtn: false });
        wx.showToast({ title: '授权成功' })
      });
    }
  },

  _updateUserInfo: function (userInfo) {
    console.log('userInfo=', userInfo);
    return updateUserInfoById(getUID(), {
      nickName: userInfo.userInfo.nickName,
      avatar: userInfo.userInfo.avatarUrl,
    }).then(res => {
      console.log('res',res);
      app.setUserInfo(res.data);
      setSTATUS(res.data.status);
    })
  }
})
